<?php
/**
 * 集成ucenter的用户管理
 * 仲伟涛
 */
//define('UC_API',true);
include_once PRODUCTION_ROOT ."/uc_client/config.inc.php";
include_once PRODUCTION_ROOT ."/uc_client/client.php";
if(!defined("SYSTEM_TIME")){
    define("SYSTEM_TIME", isset ( $_SERVER ['REQUEST_TIME'] ) ? $_SERVER ['REQUEST_TIME'] : time ());
}
class Libs_UcUser
{
    private static $loginKey = '!1@2#3%4';
    private static $loginCookieName = 'resume_auth';
    private static $adminLoginCookieName = 'resume_auth_admin';
    /**
     * 执行用户登录
     * @param array $paramArr
     * @return array
     */
    public static function userLogin($paramArr){
        $userName = trim($paramArr['username']);
        $userPwd  = $paramArr['password'];
        list($uid, $username, $password, $email) = uc_user_login($userName, $userPwd);
        $msg = '';
        if($uid > 0) {
            $msg =  '登录成功';
        } elseif($uid == -1) {
            $msg =  '用户名不存在';
        } elseif($uid == -2) {
            $msg =  '密码错误';
        } else {
            $msg =  '未定义';
        }
        return array('uid'=>$uid,'msg'=>$msg);
    }

    /**
     * 执行用户注册
     * @param array $paramArr
     * @return array
     */
    public static function userRegister($paramArr){
        $userName   = trim($paramArr['username']);
        $userPwd    = $paramArr['password'];
        $email      = trim($paramArr['email']);
        //$questionid = (int)$paramArr['questionid'];
        //$answer     = trim($paramArr['answer']);

        $uid = uc_user_register($userName, $userPwd, $email);
        $msg = '';
        if($uid <= 0) {
            if($uid == -1) {
                $msg =  '用户名不合法';
            } elseif($uid == -2) {
                $msg =  '包含要允许注册的词语';
            } elseif($uid == -3) {
                $msg =  '用户名已经存在';
            } elseif($uid == -4) {
                $msg =  'Email 格式有误';
            } elseif($uid == -5) {
                $msg =  'Email 不允许注册';
            } elseif($uid == -6) {
                $msg =  '该 Email 已经被注册';
            } else {
                $msg =  '未定义';
            }
        } else {
            $msg =  '注册成功';
        }
        return array('uid'=>$uid,'msg'=>$msg);
    }

    /**
     * 获取用户的基本信息
     * @param array $paramArr
     * @return array
     */
    public static function getUserInfo($paramArr){
        $nameOrId = $paramArr['nameOrId'];
        $flag     = $paramArr['flag'] ? 1:0; //1:使用用户 ID获取 0:(默认值) 使用用户名获取
        $rtnArr   = array();
        if($data = uc_get_user($nameOrId,$flag)) {
            $rtnArr = array(
                'uid'       => $data[0],
                'username'  => $data[1],
                'email'     => $data[2],
            );
        }
        return $rtnArr;
    }
    /**
     * 编辑用户信息
     * @param <type> $paramArr
     * @return <type>
     */
    public static function editUserInfo($paramArr){
        if (is_array($paramArr)) {
            $option = $paramArr;
            $options = array(
                'username' => '',
                'oldpw'    => '',
                'newpw'    => '', //新密码，如不修改为空
                'email'    => '', //Email，如不修改为空
                'ignoreoldpw'   => 0, //1:忽略，更改资料不需要验证密码
                'questionid'    => 0, //1:忽略，更改资料不需要验证密码
                'answer'        => '', //1:忽略，更改资料不需要验证密码
            );
            $options = array_merge($options, $paramArr);
            extract($options);
        }

        $ucresult = uc_user_edit($username, $oldpw, $newpw, $email,$ignoreoldpw);//,$questionid,$answer
        $msg = '';
        if($ucresult == -1) { //1:更新成功 0:没有做任何修改 -7:没有做任何修改 -8:该用户受保护无权限更改
            $msg =  '旧密码不正确';
        } elseif($ucresult == -4) {
            $msg =  'Email 格式有误';
        } elseif($ucresult == -5) {
            $msg =  'Email 不允许注册';
        } elseif($ucresult == -6) {
            $msg =  '该 Email 已经被注册';
        }

        return array('flag'=>$ucresult,'msg'=>$msg);
    }



    /**
     *
     * 登录，并且得到其他应用同步登录的js代码，这个代码必须输出，才能完成其他应用的同步登录
     * @param <type> $paramArr
     * @return <type>
     */
    public static function synLogin($paramArr){
        if (is_array($paramArr)) {
            $option = $paramArr;
            $options = array(
                'username' => '',
                'password'    => '',
            );
            $options = array_merge($options, $paramArr);
            extract($options);
        }

        list($uid, $username, $password, $email) = uc_user_login($username, $password);
        $msg = '';
        $synJsHtml = '';
        if($uid > 0) {
            $msg = '登录成功';
            $synJsHtml = uc_user_synlogin($uid);
        } elseif($uid == -1) {
            $msg = '用户不存在';
        } elseif($uid == -2) {
            $msg = '密码错误';
        } else {
            $msg = '未定义';
        }
        return array('uid'=>$uid,'msg'=>$msg,'synJsHtml'=>$synJsHtml);
    }


    /**
     *
     * 退出，并且得到其他应用同步退出的js代码，这个代码必须输出，才能完成其他应用的同步退出
     * @param <type> $paramArr
     * @return <type>
     */
    public static function synLogOut(){

        $synJsHtml = uc_user_synlogout();
        return $synJsHtml;
    }
    //检查mail合法性
    public static function checkMail($mail){
        $flag = uc_user_checkemail($mail);
        $msg = '';
        if($flag <= 0) {
            if($flag == -4) {
                $msg =  'Email 格式有误';
            } elseif($flag == -5) {
                $msg =  '该Email 不允许注册';
            } elseif($flag == - 6) {
                $msg =  '该Email 已经被注册';
            }
        } else {
            $msg =  '成功';
        }
        return array('flag'=>$flag,'msg'=>$msg);
    }
    
    //检查用户名合法性
    public static function checkUserName($uName){
        $flag = uc_user_checkname($uName);
        $msg = '';
        if($flag <= 0) {
            if($flag == -1) {
                $msg =  '用户名不合法';
            } elseif($flag == -2) {
                $msg =  '包含要允许注册的词语';
            } elseif($flag == - 3) {
                $msg =  '用户名已经存在';
            }
        } else {
            $msg =  '成功';
        }
        return array('flag'=>$flag,'msg'=>$msg);
    }
    /**
     *
     * 设置登录状态
     */
    public static function setLoginStatus($paramArr){
        if (is_array($paramArr)) {
            $options = array(
                'uid'      => '',
                'username' => '',
                'password' => '',
                'life'     => '',
            );
            $options = array_merge($options, $paramArr);
            extract($options);
        }
        $uid  = (int)$uid;
        $life = (int)$life;
        $life = $life ? $life + SYSTEM_TIME : 0 ;
        $uStr = self::authcode("{$uid}\t{$username}\t{$password}","ENCODE",self::$loginKey);

        setcookie(self::$loginCookieName, $uStr,$life, '/');

    }
    /**
     * 用户退出
     */
    public static function clearLoginStatus($input,$output){
        $life = SYSTEM_TIME - 100000;
        setcookie(self::$loginCookieName, ' ',$life, '/');
    }
    /**
     * 进入登录界面
     */
    public static function goToLoginPage($input,$output){
        header("Location: ?c=Login");
        exit;
    }

    public static function getLoginStatus($input,$output){
        $authStr = trim($input->cookie(self::$loginCookieName));
        $authArr = array();
        if($authStr){
            $authArrStr = self::authcode($authStr,"DECODE",self::$loginKey);
            $authArr = explode("\t",$authArrStr);
        }
        return $authArr;
    }
    //验证是否登录
    public static function checkLogin($input,$output){

        $loginArr = Libs_UcUser::getLoginStatus($input,$output);

        $uid = 0;
        if(is_array($loginArr)){
            $uid = isset($loginArr[0]) ? (int)$loginArr[0] : 0;

        }
        if(!$uid && $input->jumpLogin){
            self::goToLoginPage($input,$output);
        }
        return array(
            'uid'      => $uid ,
            'userName' => isset($loginArr[1]) ? trim($loginArr[1]) : '',
            'passWord' => isset($loginArr[2]) ? trim($loginArr[2]) : '',
            );
    }
    /**
     *
     * 加密解密函数
     */
    public static function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
        $ckey_length = 4;

        $key = md5($key ? $key : UC_KEY);
        $keya = md5(substr($key, 0, 16));
        $keyb = md5(substr($key, 16, 16));
        $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

        $cryptkey = $keya.md5($keya.$keyc);
        $key_length = strlen($cryptkey);

        $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
        $string_length = strlen($string);

        $result = '';
        $box = range(0, 255);

        $rndkey = array();
        for($i = 0; $i <= 255; $i++) {
            $rndkey[$i] = ord($cryptkey[$i % $key_length]);
        }

        for($j = $i = 0; $i < 256; $i++) {
            $j = ($j + $box[$i] + $rndkey[$i]) % 256;
            $tmp = $box[$i];
            $box[$i] = $box[$j];
            $box[$j] = $tmp;
        }

        for($a = $j = $i = 0; $i < $string_length; $i++) {
            $a = ($a + 1) % 256;
            $j = ($j + $box[$a]) % 256;
            $tmp = $box[$a];
            $box[$a] = $box[$j];
            $box[$j] = $tmp;
            $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
        }

        if($operation == 'DECODE') {
            if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
                return substr($result, 26);
            } else {
                    return '';
                }
        } else {
            return $keyc.str_replace('=', '', base64_encode($result));
        }

    }

    public static function uploadAvatar($paramArr){
        if (is_array($paramArr)) {
            $options = array(
                'uid'      => '',
                'type'     => 1,//1  真是，2 虚拟
                'getHtml'  => true,//是否获得html，flase返回flash数组
            );
            $options = array_merge($options, $paramArr);
            extract($options);
        }
        $uid  = (int)$uid;
        $type = (int)$type;
        return uc_avatar($uid, $type == 1 ? 'real' : 'virtual', $getHtml);
    }

    //返回头像
    public static function getAvatar($paramArr){
        if (is_array($paramArr)) {
            $options = array(
                'uid'      => '',
                'type'     => 1,//1  真是，2 虚拟
                'size'    => 'big',//big middle small
            );
            $options = array_merge($options, $paramArr);
            extract($options);
        }
        $uid  = (int)$uid;
        if(!$uid) return '';
        $type = (int)$type;
        $type = $type == 1 ? 'real' : 'virtual';
        return UC_API . "/avatar.php?uid={$uid}&type={$type}&size={$size}";
    }

    // 后台用户退出
    public static function clearAdminLoginStatus($input,$output){
        $life = SYSTEM_TIME - 100000;
        setcookie(self::$adminLoginCookieName, ' ',$life, '/');
    }
    //获得后台登录的数据
    public static function getAdminLoginInfo(ME_Request $input, ME_Response $output){

        $authStr = trim($input->cookie(self::$adminLoginCookieName));
        $authArr = array();
        if($authStr){
            $authArrStr = self::authcode($authStr,"DECODE",self::$loginKey);
            $authArr = explode("\t",$authArrStr);
        }
        //return array('lala','lala');
        if(empty($authArr) && $input->doJump){
            echo '<script>window.location.href="index.php?c=Login";top.window.location.href="index.php?c=Login";</script>';
            exit;
        }
        return $authArr;
    }
    public static function checkAdminLogin($username,$passwd){
        if(empty($username) || empty($passwd)){
            return false;
        }
        $tmpPassMap = array(
            'lala' => 'meimima',
            'guoguo' => 'woailala',
            'wolf' => 'woailala',
        );
        if(isset($tmpPassMap[$username])  && $passwd == $tmpPassMap[$username]){
            $uStr = self::authcode("{$username}\t{$passwd}","ENCODE",self::$loginKey);
            setcookie(self::$adminLoginCookieName, $uStr,$life, '/');
            return true;
        }
        $db = Db_Admin::instance();
        $sql = "SELECT a.*, m.* FROM ".UC_DBTABLEPRE."admins a LEFT JOIN ".UC_DBTABLEPRE."members m USING(uid) WHERE a.username='$username'";
        $resm = $db->getRow($sql);
        $salt = $resm['salt'];
        $dbpass = $resm['password'];
        if(md5(md5($passwd).$salt) == $dbpass){

            $uid  = (int)$uid;
            $uStr = self::authcode("{$username}\t{$passwd}","ENCODE",self::$loginKey);
            setcookie(self::$adminLoginCookieName, $uStr,$life, '/');
            return true;
        }
        return false;
        
    }
}

?>
